import request from '../../utils/request';
import { getUserLevel,DIFFICULTY_LEVELS } from '../../utils/constants';

// pages/user-center/user-center.js
Page({
  data: {
    showEdit: false,
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    levelProgress: {
      beginner: 0,
      intermediate: 0,
      advanced: 0
    },
    levels:{
      beginner:20,
      intermediate:10,
      advanced:10,
    },
    levelNames: {
      beginner: '初级',
      intermediate: '中级',
      advanced: '高级'
    },
    levelColors: {
      beginner: '#10B981',
      intermediate: '#F59E0B',
      advanced: '#EF4444'
    },
    statistics: {
      totalScore: 0,
      completedLevels: 0,
      checkinDays: 0,
      hintsUsed: 0,
      friendHelps: 0
    }
  },

  onLoad: function (options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
  },

  onShow: function () {
    // 获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      const userInfo = app.globalData.userInfo;
      // 获取用户等级信息
      const levelInfo = getUserLevel(userInfo.score || 0);
      userInfo.level = levelInfo.name;
      userInfo.levelClass = levelInfo.levelClass;
      userInfo.className = levelInfo.className;
      userInfo.avatarLargeClass = levelInfo.avatarLargeClass;  // 添加大头像边框样式类

      this.setData({
        userInfo,
        hasUserInfo: true
      });
      
      // 计算关卡进度
      this.calculateLevelProgress();
      
      // 计算统计数据
      this.calculateStatistics();

      this.loadLevels()
    }
  },

  loadLevels:function(){
    request({
      url: '/levels',
      method: 'GET'
    })
      .then(res => {
        // 确保获取 list 数组
        const levelsData = res.data.list || [];
        const beginner = levelsData.filter(level => level.difficulty === DIFFICULTY_LEVELS.beginner).length;
        const intermediate = levelsData.filter(level => level.difficulty === DIFFICULTY_LEVELS.intermediate).length;
        const advanced = levelsData.filter(level => level.difficulty === DIFFICULTY_LEVELS.advanced).length;

        this.setData({ levels:{
          beginner,
          intermediate,
          advanced
        } });
      })
      .catch(err => {
        console.error('加载关卡失败:', err);
        wx.showToast({
          title: '加载关卡失败',
          icon: 'none'
        });
      });
  },
  
  // 计算关卡进度
  calculateLevelProgress: function() {
    const app = getApp();
    const completedLevels = this.data.userInfo.completedLevels || [];
    
    // 计算各难度完成进度
    const beginnerCompleted = completedLevels.filter(level => level.startsWith('beginner_')).length;
    const intermediateCompleted = completedLevels.filter(level => level.startsWith('intermediate_')).length;
    const advancedCompleted = completedLevels.filter(level => level.startsWith('advanced_')).length;
    
    // 更新全局进度
    // app.globalData.levelProgress = {
    //   beginner: beginnerCompleted,
    //   intermediate: intermediateCompleted,
    //   advanced: advancedCompleted
    // };
  
    this.setData({
      levelProgress:  {
        beginner: beginnerCompleted,
        intermediate: intermediateCompleted,
        advanced: advancedCompleted
      }
    });
  },
  
  // 计算统计数据
  calculateStatistics: function() {
    const userInfo = this.data.userInfo;
    const completedLevels = userInfo.completedLevels || [];
    
    this.setData({
      'statistics.totalScore': userInfo.score || 0,
      'statistics.completedLevels': completedLevels.length,
      'statistics.checkinDays': userInfo.checkinDays || 0,
      // 这两项数据可能需要从其他地方获取，这里暂时设为0
      'statistics.hintsUsed': 0,
      'statistics.friendHelps': 0
    });
  },

  // 获取用户信息
  getUserProfile: function() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        // 更新用户信息到数据库
        this.updateUserInfo(res.userInfo);
      },
      fail: (err) => {
        console.error('获取用户信息失败', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    });
  },
  closeEdit: function() {
    if (this.data.userInfo) {
      this.setData({
        showEdit: false,
      });
    }
  },
  // 编辑个人信息弹窗
  editProfile: function() {
    if (!this.data.userInfo) {
      this.setData({
        showEdit: true,
      });
    } else {
      this.setData({
        showEdit: !this.data.showEdit,
      });
    }
  },
  // 更新用户信息到数据库
  
  // 跳转到每日签到页面
  navigateToDailyCheck: function() {
    wx.navigateTo({
      url: '/pages/daily-check/daily-check'
    });
  },
  
  // 跳转到难度选择页面
  navigateToLevelSelect: function() {
    wx.navigateTo({
      url: '/pages/level-select/level-select'
    });
  },
  
  // 跳转到排行榜页面
  navigateToRank: function() {
    wx.switchTab({
      url: '/pages/rank/rank'
    });
  },
  
  // 清除缓存
  clearCache: function() {
    wx.showModal({
      title: '提示',
      content: '确定要清除缓存吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorage({
            success: () => {
              wx.showToast({
                title: '缓存已清除',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },
  
  // 关于我们
  showAbout: function() {
    wx.showModal({
      title: '关于看图猜成语',
      content: '看图猜成语是一款益智类小游戏，通过图片提示猜测成语，寓教于乐，提高文化素养。\n\n版本：1.0.6\n开发者：看图猜成语团队',
      showCancel: false
    });
  },
    // 保存后触发更新 toDo 昵称更新了，头像403
    onUserInfoUpdated(event) {
      const { user } = event.detail;
      this.setData({ user });
    },
  
  // 用户反馈
  submitFeedback: function() {
    wx.showModal({
      title: '意见反馈',
      content: '感谢您的使用，如有任何建议或问题，请联系我们\n微信: WGF184929',
      showCancel: false
    });
  }
});